﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using HtmlAgilityPack;
using KM.ENT;
using KM.BUS;
namespace KM.Controllers.Admin
{
    public class KhuyenMaiController : BaseController
    {
            //
        // GET: /KhuyenMai/

        public ActionResult Index()
        {
            
            return View();
        }
        public List<SelectListItem> getState(string check)
        {
            busLoaiKhuyenMai busLKM = new busLoaiKhuyenMai();
            List<entLoaiKhuyenMai> lst=new List<entLoaiKhuyenMai>();
            lst = busLKM.getAll();
            //lap de lay list item dua vao dropdownlist
            List<SelectListItem> items = new List<SelectListItem>();
            foreach (var item in lst)
            {
                items.Add(new SelectListItem()
                {
                    Value = item.LoaiKhuyenMaiId.ToString(),
                    Text = item.TenLoaiKhuyenMai,
                    Selected=(item.LoaiKhuyenMaiId.ToString()==check?true:false)
                });
            }
            
           
           
            return items;
        }
        public ActionResult DanhSach()
        {

            ViewBag.stateList = getState("0");
            busKhuyenMai busKM = new busKhuyenMai();
            List<entKhuyenMai> lst = new List<entKhuyenMai>();
            lst = busKM.getAll(1);

            return View(lst);
        }
        [HttpPost]
        public ActionResult DanhSach( FormCollection collection)
        {

            ViewBag.stateList = getState(collection["lmk"].ToString());
            busKhuyenMai busKM = new busKhuyenMai();
            List<entKhuyenMai> lst = new List<entKhuyenMai>();
            lst = busKM.getAll(int.Parse(collection["lmk"].ToString()));

            return View(lst);
        }
        static int k = 0;
        public string DownloadImageFromUrl(string imageUrl)
        {
            System.Drawing.Image image = null;

            try
            {
                System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
                webRequest.AllowWriteStreamBuffering = true;
                webRequest.Timeout = 30000;

                System.Net.WebResponse webResponse = webRequest.GetResponse();

                System.IO.Stream stream = webResponse.GetResponseStream();

                image = System.Drawing.Image.FromStream(stream);

                webResponse.Close();
                string filename = DateTime.Now.ToString("ddmmyyhhmmss").ToString() + k++.ToString() + ".jpg";
                image.Save(Server.MapPath("/images/" + filename));
                return filename;
            }
            catch (Exception ex)
            {

            }
            return "";
        }
        public ActionResult LayKhuyenMai()
        {
            return View();
        }
        [HttpPost]
        public ActionResult LayKhuyenMai(FormCollection collection)
        {

            //khuyenmaivang.com
            //string nodeRoot = "div[@class=\"deal-list\"]";
            //string nodeImage = "div[@class=\"img-deal\"]/a/img";
            //string nodeTieuDe = "./h2/a";
            string url = collection["focusedInput"].ToString();
            string nodeRoot = "//ul[@class=\"listdeal\"]";
            string nodeImage = "div[@class='thumb']/a/img";
            string nodeTieuDe = "div/h2/a";
            string nodeGiaNiemYet = "div/span[@class='sell-price']";
            string nodeGiaKM = "//span[@class='original-price']";
            string nodeThoiGian = "div/div[@class='time']/span";



            entKhuyenMai entKM = new entKhuyenMai();
            List<entKhuyenMai> lst = new List<entKhuyenMai>();
            HtmlWeb htmlWeb = new HtmlWeb();
            // Creates an HtmlDocument object from an URL
            HtmlAgilityPack.HtmlDocument document = htmlWeb.Load(url);
           // var nodes = document.DocumentNode.Descendants("div").Where(d => d.Attributes.Contains("class") && d.Attributes["class"].con);
            var nodes = from foo in document.DocumentNode.Descendants("div")
                        where foo.Attributes["class"] != null && foo.Attributes["class"].Value.Contains("span4 product-item")
                        select foo;

            int i = 0;
            if (nodes!=null)
            {
                foreach (HtmlAgilityPack.HtmlNode item in nodes)
                {
                    entKM = new entKhuyenMai();
                    HtmlNode img = item.SelectSingleNode(nodeImage);
                    if (img != null)
                    {
                        entKM.ImageSmall = DownloadImageFromUrl(img.Attributes["data-original"].Value);
                        
                    }

                    HtmlNode a = item.SelectSingleNode(nodeTieuDe);
                    entKM.TieuDe = a.InnerHtml;
                    HtmlNode node = item.SelectSingleNode(nodeThoiGian);
                    //lay thoi gian ban
                    entKM.ThoiGian = node.InnerHtml;
                    //lay gia niem yet
                    node = item.SelectSingleNode(nodeGiaNiemYet);
                    entKM.GiaBan = node.InnerText;

                    //lay gia khuyen mai
                    node = item.SelectSingleNode(nodeGiaKM);
                    entKM.GiaKM = node.InnerText;

                    lst.Add(entKM);
                }
                
            }
            ViewBag.me = lst.Count;
            return Redirect("/KMAdmin");
        }
        [HttpPost]
        public PartialViewResult getKhuyenMaiPartialView(FormCollection collection)
        {
            List<entKhuyenMai> lst = new List<entKhuyenMai>();
            busKhuyenMai busKM = new busKhuyenMai();
            lst = busKM.getAll(int.Parse(collection["lmk"].ToString()));
            return PartialView(lst);
        }

    }
}
